package top.dark.member.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import top.dark.common.utils.PageUtils;
import top.dark.common.utils.Query;
import top.dark.member.dao.MemberDao;
import top.dark.member.dao.MemberLevelDao;
import top.dark.member.entity.MemberEntity;
import top.dark.member.entity.MemberLevelEntity;
import top.dark.member.exception.PhoneExistException;
import top.dark.member.exception.UsernameExistException;
import top.dark.member.service.MemberService;
import top.dark.member.vo.RegisterVo;
import top.dark.member.vo.SocialGithubUserVo;
import top.dark.member.vo.UserLoginVo;

@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(RegisterVo vo) throws UsernameExistException, PhoneExistException {
        MemberEntity memberEntity = new MemberEntity();

        // 设置会员等级
        MemberLevelEntity defaultLevel = memberLevelDao.defaultLevel();
        if (defaultLevel != null) {
            memberEntity.setLevelId(defaultLevel.getId());
        }

        // 校验传递过来的手机号和用户名、是否唯一，将异常抛出让controller感知异常
        checkedExistUsername(vo.getUserName());
        checkedExistPhone(vo.getPhone());

        // 设置传递过来的信息
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());

        // 密码需要加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        // TODO 其他默认信息

        // 保存
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkedExistUsername(String userName) throws UsernameExistException {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>()
                .eq("username", userName));
        if (count != null && count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public void checkedExistPhone(String phone) throws PhoneExistException {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>()
                .eq("mobile", phone));
        if (count != null && count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(UserLoginVo vo) {
        String loginAcct = vo.getLoginAcct();
        String password = vo.getPassword();
        // 从数据库中查出登录用户信息
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginAcct).or().eq("mobile", loginAcct));
        if (memberEntity != null) {
            // 用户密码匹配
            String passwordDB = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, passwordDB);
            if (matches) {
                // 登录成功
                return memberEntity;
            }
        }
        return null;
    }

    @Override
    public MemberEntity oauthGithubLogin(SocialGithubUserVo vo) {
        // 判断社交账号是否已经注册过系统
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", vo.getId()));
        if (entity != null) {
            // 用户已经注册过，更新用户令牌信息
            MemberEntity updateMember = new MemberEntity();
            updateMember.setId(entity.getId());
            updateMember.setAccessToken(vo.getAccessToken());
            // 1秒 - 1000毫秒，10分钟 - 600秒 - 600000毫秒，github默认accessToken有效期是10分钟
            updateMember.setExpiresIn(System.currentTimeMillis() + 600000L + "");
            baseMapper.updateById(updateMember);
            return entity;
        } else {
            // 用户没注册过，自动给用户注册
            MemberEntity register = new MemberEntity();
            register.setSocialUid(vo.getId());
            register.setAccessToken(vo.getAccessToken());
            register.setExpiresIn(System.currentTimeMillis() + 600000L + "");
            register.setNickname(vo.getName());
            register.setCity(vo.getLocation());
            baseMapper.insert(register);
            return register;
        }
    }

}